import {
	getUserInfo,
	userLocation,
	getCountTabs,
	sendLocationError
} from "@/api"
import dayjs from 'dayjs'
import {
	cache,
	toast,
	rep
} from "@/utils"
import permision from "@/js_sdk/wa-permission/permission"
import {
	checkSystemEnableLocation
} from "@/utils/permision"
import coordtransform from "coordtransform"
import {
	reject
} from "lodash"
let loginFlag = false
let modalFalg = false
let modalFalg2 = false
const state = {
	// 用户信息
	userInfo: {},
	userMenu: [],
	// 订单是否没有拨打电话和填写报价单
	orderStatus: {
		id: "",
		step: 0
	},
	locationTimerId: null,
	location: {
		latitude: null,
		longitude: null
	},
	pushClientid: "", // 推送标识
	// 送返修全部订单
	repatCount: 0
}

const mutations = {
	SET_USER_INFO(state, data) {
		state.userInfo = data;
	},
	SET_MODAL_INDEX(state, data) {
		state.modalIndex = data;
	},
	SET_ORDER_STATUS(state, data) {
		state.orderStatus = {
			...state.orderStatus,
			...data
		}
	},
	SET_MODAL_STATUS(state, data) {
		state.modalFlag = data
	},
	SET_USER_MENU(state, data) {
		state.userMenu = data;
	},
	SET_LOCATION_TIMER_ID(state, data) {
		state.locationTimerId = data
	},
	SET_LOCATION(state, data) {
		state.location = data
	},
	SET_PUSH_CLIENT_ID(state, data) {
		state.pushClientid = data;
	},
	SET_REPAT_COUNT(state, data) {
		state.repatCount = data
		try {
			if (data > 0) {
				uni.setTabBarBadge({
					index: 1,
					text: `${data > 99 ? "99+" : (data+"")}`
				})
				return
			}
			uni.removeTabBarBadge({
				index: 1
			})
		} catch (e) {
			//TODO handle the exception
		}
	},
}

const actions = {
	getUserInfo({
		commit,
		state,
		dispatch
	}) {
		return new Promise((resolve, reject) => {
			getUserInfo("userCenter").then(res => {
				resolve(res)
				console.log(res, '用户信息')
				if (res.code === 1) {
					commit("SET_USER_INFO", res.data)
					commit("SET_USER_MENU", res.data.menuGroupList || [])
					dispatch("getPushClientId", res.data.id)
				}
			}).catch(e => reject(e))
		})
	},
	// 退出登录
	logout({
		commit
	}) {
		cache.clearAll().then(() => {
			// toast("退出成功")
			commit("SET_USER_INFO", {})
			commit("SET_USER_MENU", [])
			setTimeout(() => uni.reLaunch({
				url: '/pages/login/index'
			}))
		}).catch(er => {
			console.log(er, 'logout')
		})
	},
	// 定位更新
	location({
		commit,
		state,
		dispatch
	}) {
		// console.log(permision.judgeIosPermission("location"),'权限检测')
		!state.locationTimerId && dispatch("getUserLocation")
		const timerId = setInterval(() => {
			commit("SET_LOCATION_TIMER_ID", timerId)
			dispatch("getUserLocation")
		}, 1 * 60 * 1000)
	},
	clearLocation({
		commit,
		state
	}) {
		clearInterval(state.locationTimerId)
	},
	getUserLocation({
		dispatch,
		state,
		commit
	}, type) {
		let sysInfo = {}
		uni.getSystemInfo({
			success: r => {
				sysInfo = r
			}
		})
		// #ifdef APP-PLUS
		const localtion = checkSystemEnableLocation()
		// 是否开启定位权限 
		if (!localtion) {
			return dispatch('localtionCheck')
		}
		return new Promise((resolve, reject) => {
			getLocation().then(res => {
				resolve(res)
				uni.removeStorageSync('errNumber')
				dispatch("sendLocation", res)
			}).catch(async err => {
				reject(err)
				// 如果是更新位置的则不发送任何请求
				if (type == 'btn') return
				// 获取错误次数 如果大于3次就提示用户定位错误
				let errNumber = uni.getStorageSync('errNumber') || 0
				uni.setStorageSync('errNumber', ++errNumber)
				errNumber = uni.getStorageSync('errNumber')
				// 出现第九次让他去设置页
				if (errNumber >= 9) {
					sendLocationFailTwo('您的定位异常请检查定位权限')
					uni.removeStorageSync('errNumber')
				}
				uniCloud.callFunction({
					name: "sendLocationFail",
					data: {
						userId: state.userInfo.id,
						brand: sysInfo.brand,
						deviceId: sysInfo.deviceId,
						system: sysInfo.platform + '/' + sysInfo.osVersion,
						error: JSON.stringify({
							type: 'plus.geolocation.getCurrentPosition',
							error: err
						}),
						json: JSON.stringify(sysInfo),
						time: dayjs(Date.now()).format("YYYY-MM-DD HH:mm:ss")
					}
				})
				console.log('定位失败', err, state.userInfo.id)
				// 获取上一次的经纬度 如果有值的情况则上传
				if (state?.localtion?.x && state?.localtion?.y) {
					const obj = {
						longitude: state.localtion.x,
						latitude: y,
						type: 'wgs84'
					}
					console.log('发送上一次请求的经纬度', obj)
					dispatch("sendLocation", obj)
				}
			})
		})
		return

		// #endif
	},
	getPushClientId({
		commit
	}, userId) {
		// #ifdef APP-PLUS
		uni.getPushClientId({
			success(info) {
				commit("SET_PUSH_CLIENT_ID", info.cid)
				uniCloud.callFunction({
					name: "setUserInfo",
					data: {
						cid: info.clientid ?? info.cid,
						userId: userId
					}
				}).then(res => {
					cache.set.pushCid(info.clientid ?? info.cid)
					console.log(res, '云函数执行成功')
				}).catch(err => {
					console.log(err, '云函数执行失败')
				})
			}
		})
		// #endif
	},
	getOrderCount({
		commit
	}, type = "worker_repair") {
		getCountTabs(type).then(res => {
			if (res.code === 1 && res.data) {
				commit("SET_REPAT_COUNT", res.data.all || 0)
			}

		})
	},
	sendLocation(context, coords) {
		let sysInfo = {}
		uni.getSystemInfo({
			success: r => {
				sysInfo = r
			}
		})
		const coordsType = coords.type
		// const {
		// 	coordsType,
		// 	coords
		// } = data
		let coordinate = [coords.longitude, coords.latitude]
		if (coordsType === 'wgs84') {
			coordinate = coordtransform.wgs84togcj02(coords.longitude, coords.latitude)
		} else if (coordsType === 'gcj02') {
			coordinate = [coords.longitude, coords.latitude]
		} else if (coordsType === 'bd09') {
			coordinate = coordtransform.bd09togcj02(coords.longitude, coords.latitude)
		}
		console.log(`
			坐标类型: ${coordsType}
			原始经度：${coords.longitude}
			原始维度：${coords.latitude}
			经纬度JSON：${JSON.stringify(coordinate)}
		`)
		userLocation(coordinate[0], coordinate[1]).then(res => {
			console.log(res, '定位接口调用成功')
			context.commit('SET_LOCATION', {
				x: coordinate[0],
				y: coordinate[1],
				time: Date.now()
			})
		}).catch(err => {
			console.log("定位调用失败", err)
			sendLocationError({
				brand: sysInfo.brand,
				deviceId: sysInfo.deviceId,
				system: sysInfo.platform + '/' + sysInfo.osVersion,
				error: JSON.stringify({
					type: 'api/userLocation',
					error: err
				}),
				json: JSON.stringify(sysInfo),
				time: Date.now()
			}).then(res => {
				console.log(res, '发送成功')
			})
		})
	},
	localtionCheck({
		dispatch,
		state,
		commit
	}, content) {
		// 判断是否开启权限
		if (!loginFlag && !checkSystemEnableLocation() || content) {
			loginFlag = true
			uni.showModal({
				title: '提示',
				content: content || '获取定位失败，是否授权打开定位',
				showCancel: false,
				success: (res) => {
					if (res.confirm) {
						loginFlag = false
						uni.getSystemInfo({
							success: (sys) => {
								if (sys.platform == 'ios') {
									plus.runtime.openURL(
										"app-settings://");
								} else {
									var main = plus.android
										.runtimeMainActivity();
									var Intent = plus.android
										.importClass(
											"android.content.Intent");
									//可能应该直接进入应用列表的权限设置？=> android.settings.APPLICATION_SETTINGS
									var mIntent = new Intent(
										'android.settings.LOCATION_SOURCE_SETTINGS'
									);
									main.startActivity(mIntent);
								}
							}
						})
					}
					if (!res.confirm) {
						loginFlag = false
						dispatch('localtionCheck')
					}
				}
			})
		}
	}
}

function sendLocationFail(content) {
	if (!modalFalg) {
		modalFalg = true
		uni.showModal({
			title: '提示',
			content,
			showCancel: false,
			complete() {
				// 不管是 确认还是取消 让弹窗继续
				modalFalg = false
			}
		})
	}

}

function sendLocationFailTwo(content) {
	// 判断是否开启权限
	if (!modalFalg2) {
		modalFalg2 = true
		uni.showModal({
			title: '提示',
			content: content,
			showCancel: false,
			success: (res) => {
				modalFalg2 = false
				if (res.confirm) {
					uni.getSystemInfo({
						success: (sys) => {
							if (sys.platform == 'ios') {
								plus.runtime.openURL(
									"app-settings://");
							} else {
								var main = plus.android
									.runtimeMainActivity();
								var Intent = plus.android
									.importClass(
										"android.content.Intent");
								//可能应该直接进入应用列表的权限设置？=> android.settings.APPLICATION_SETTINGS
								var mIntent = new Intent(
									'android.settings.LOCATION_SOURCE_SETTINGS'
								);
								main.startActivity(mIntent);
							}
						}
					})
				}
			}
		})
	}
}

function getLocation() {
	return new Promise((resolve, reject) => {
		uni.getLocation({
			success: resolve,
			fail: reject
		})
	})
}
export default {
	namespaced: true,
	state,
	mutations,
	actions
}